<template>
  <NavBar title="资源包记录" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="resource-record-container">
    
    <!-- 标签页导航 -->
    <view class="tab-navigation">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: activeTab === index, left:tab.name === '全部', right:tab.name === '使用'}"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
        <view class="tab-indicator" v-if="activeTab === index"></view>
      </view>
    </view>
    
    <!-- 记录列表 -->
    <scroll-view
      class="record-scroll-view"
      scroll-y="true"
      @scrolltolower="onScrollToLower"
      lower-threshold="100"
      refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="loading"
    >
      <view class="record-list" v-if="filteredRecords.length > 0">
        <view
          v-for="(record, index) in filteredRecords"
          :key="record.id || index"
          class="record-item"
        >
          <view class="record-content">
            <view class="record-left">
              <text class="record-desc">{{ record.description }}</text>
              <text class="record-date">{{ record.date }}</text>
            </view>
            <view class="record-right">
              <text
                class="record-value"
                :class="record.type === 'gain' ? 'value-gain' : 'value-consume'"
              >
                {{ record.type === 'gain' ? '+' : '-' }} {{ record.value }}
              </text>
            </view>
          </view>
          <view class="record-divider" v-if="index < filteredRecords.length - 1"></view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="load-more" v-if="loading || hasMore">
        <view v-if="loading" class="loading-text">
          <text>加载中...</text>
        </view>
        <view v-else-if="hasMore" class="load-more-text">
          <text>上拉加载更多</text>
        </view>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && filteredRecords.length > 0">
        <text class="no-more-text">没有更多数据了</text>
      </view>
         <!-- 空状态 -->
    <view class="empty-state" v-if="filteredRecords.length === 0 && !loading">
      <image class="empty-icon" src="/static/empty.png" mode="widthFix"></image>
      <text class="empty-text">暂无记录</text>
    </view>
    </scroll-view>
    
 
  </view>
  </NavBar>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { WALLET_API } from '../../config/api.js'
import { getToken, isLoggedIn } from '../../utils/user.js'

// 响应式数据
const activeTab = ref(0)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(false)

// 标签页数据
const tabs = ref([
  { name: '全部', type: 'all', openType: null },
  { name: '收入', type: 'gain', openType: 1 },
  { name: '使用', type: 'consume', openType: 2 }
])

// 记录数据 - 从API获取
const records = ref([])

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 处理API数据为显示格式
const processRecordData = (apiData) => {
  if (!apiData || !apiData.logs) {
    return []
  }

  return apiData.logs
    .filter(item => item.biz_type !== 'GENESIS') // 过滤掉 biz_type 为 GENESIS 的数据
    .map(item => ({
      id: item.id,
      description: item.memo || '资源包记录',
      date: formatDateTime(item.created_at),
      value: Math.abs(item.delta_balance) || 0,
      type: item.delta_balance > 0 ? 'gain' : 'consume',
      rawData: item // 保存原始数据
    }))
}

// 计算属性 - 显示处理后的记录
const filteredRecords = computed(() => {
  return processRecordData({ logs: records.value || [] })
})

// 获取资源包记录列表
const fetchResourceRecords = async (reset = false) => {
  if (loading.value) return

  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    console.log('用户未登录，不请求资源包记录接口')
    records.value = []
    return
  }

  try {
    loading.value = true

    if (reset) {
      currentPage.value = 1
      records.value = []
      hasMore.value = true
    }

    const token = getToken()
    if (!token) {
      console.error('未找到用户token')
      return
    }

    // 构建请求参数
    const params = {
      asset_code: 'PKG_CREDIT',
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 根据当前标签页添加操作类型过滤
    const currentTab = tabs.value[activeTab.value]
    if (currentTab.openType !== null) {
      params.open_type = currentTab.openType
    }

    // 构建查询字符串
    const queryString = Object.keys(params)
      .filter(key => params[key] !== null && params[key] !== undefined)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    const response = await uni.request({
      url: `${WALLET_API.LOGS}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('资源包记录API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const responseData = response.data.data || {}
      const newData = responseData.logs || []

      if (reset) {
        records.value = newData
      } else {
        records.value = [...records.value, ...newData]
      }

      // 根据has_more字段判断是否还有更多数据
      hasMore.value = responseData.has_more || false

      console.log('资源包记录加载成功:', {
        currentPage: currentPage.value,
        currentDataCount: records.value.length,
        hasMore: hasMore.value,
        newDataLength: newData.length,
        total: responseData.total || 0
      })
    } else {
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取资源包记录失败'
      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }

  } catch (error) {
    console.error('获取资源包记录失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

const switchTab = (index) => {
  activeTab.value = index
  // 切换标签页时重新加载数据
  fetchResourceRecords(true)
}

// 下拉刷新
const onRefresh = () => {
  console.log('下拉刷新')
  fetchResourceRecords(true)
}

// 上拉加载更多
const onScrollToLower = () => {
  console.log('滚动到底部，检查是否需要加载更多数据')

  // 如果正在加载或没有更多数据，则不执行
  if (loading.value || !hasMore.value) {
    console.log('跳过加载：', { loading: loading.value, hasMore: hasMore.value })
    return
  }

  console.log('开始加载下一页数据，当前页：', currentPage.value)

  // 增加页码并加载下一页
  currentPage.value++
  fetchResourceRecords(false)
}

// 页面加载时获取数据
onMounted(() => {
  console.log('资源包记录页面加载')
  fetchResourceRecords(true)
})
</script>

<style scoped>
.resource-record-container {
  min-height: 100vh;
 background: linear-gradient( 180deg, #C2DDFF 0%, #FFFFFF 100%);
 border-radius: 0rpx 0rpx 0rpx 0rpx;
  position: relative;
  padding-top: 160rpx;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #000;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.3);
}

.back-icon {
  font-size: 32rpx;
  color: white;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: white;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-placeholder {
  width: 60rpx;
  height: 60rpx;
  background: white;
  border-radius: 8rpx;
}

/* 标签页导航 */
.tab-navigation {
  display: flex;
  margin: 0 20rpx;
  border-radius: 16rpx 16rpx 0 0;
  padding-top: 20rpx;
}

.tab-item {
  flex: 1;
  position: relative;
  padding: 20rpx 20rpx;
  text-align: center;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
}



.tab-text {
  font-size: 28rpx;
  font-weight: 500;
  color: #666;
  transition: all 0.3s ease;
}



.tab-indicator {

  width: 60rpx;
  height: 4rpx;
  background: #9C27B0;
  border-radius: 2rpx;
}

/* 滚动视图 */
.record-scroll-view {
  height: calc(100vh - 200rpx);
  margin: 10rpx 30rpx 0;
  background: #FFFFFF;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  width: 92%;
}

/* 记录列表 */
.record-list {
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.record-item {
  position: relative;
}

.record-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 30rpx;
}

.record-left {
  flex: 1;
  margin-right: 20rpx;
}

.record-desc {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 12rpx;
  line-height: 1.4;
}

.record-date {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.record-right {
  display: flex;
  align-items: center;
}

.record-value {
  font-size: 32rpx;
  font-weight: 600;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  min-width: 80rpx;
  text-align: center;
}

/* 收入样式 */
.value-gain {
  color: #4CAF50;
}

/* 消耗样式 */
.value-consume {
  color: #F44336;
}



.left{
	align-items:flex-start!important;
}
.right{
		align-items:flex-end!important;
}

/* 分割线 */
.record-divider {
  height: 1rpx;
  background: repeating-linear-gradient(
    to right,
    #8B8B8B 0rpx,
    #8B8B8B 8rpx,
    transparent 8rpx,
    transparent 16rpx
  );
  margin: 0 30rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
  background: white;
  margin: 0 20rpx;
}

.empty-icon {
  width: 146rpx;
  height: 200rpx;
  margin-top: 250rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #666;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .record-content {
    padding: 24rpx;
  }
  
  .record-desc {
    font-size: 26rpx;
  }
  
  .record-value {
    font-size: 28rpx;
  }
  
  .tab-item {
    padding: 24rpx 16rpx;
  }
  
  .tab-text {
    font-size: 26rpx;
  }
}

/* 加载更多样式 */
.load-more {
  padding: 30rpx 0;
  text-align: center;
}

.loading-text {
  color: #999999;
  font-size: 28rpx;
}

.load-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}

.no-more {
  padding: 30rpx 0;
  text-align: center;
}

.no-more-text {
  color: #CCCCCC;
  font-size: 28rpx;
}

/* 安全区域适配 */
@supports (padding: max(0px)) {
  .resource-record-container {
    padding-bottom: max(0px, env(safe-area-inset-bottom));
  }
}
</style>

